<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 行标签 -->
      <el-row :gutter="20">
        <!-- 列标签 -->
        <el-col :span="10">
          <!-- 输入框 -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUsersList">
            <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="3">
          <!-- 按钮 -->
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="UsersList" stripe border>
        <!-- 索引列 type="index" -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="modifyUserStatus(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="acquireUsers(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="rmUserId(scope.row.id)"></el-button>
            </el-tooltip>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="getAssigningRolse(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 添加用户的对话框 -->
      <!-- close:关闭事件 -->
      <el-dialog title="添加用户" :visible.sync="dialogVisible" width="30%" @close="addDialogClosed">
        <!-- 这是主题区域 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
          <!-- 用户名 -->
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <!-- 密码 -->
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="addForm.password"></el-input>
          </el-form-item>
          <!-- 邮箱 -->
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <!-- 手机号 -->
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 这是底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改弹窗 -->
      <el-dialog
        title="修改用户"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClosed"
      >
        <el-form :model="editUsers" :rules="editUserRules" ref="editUserRef" label-width="70px">
          <!-- 用户名 -->
          <el-form-item label="用户名">
            <el-input v-model="editUsers.username" disabled></el-input>
          </el-form-item>
          <!-- 邮箱 -->
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUsers.email"></el-input>
          </el-form-item>
          <!-- 手机 -->
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editUsers.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog title="提示" :visible.sync="assigningRolseVisible" width="50%" @close="setRolesClose">
        <div>
          <p>当前的用户:{{userInfo.username}}</p>
          <p>当前的用户:{{userInfo.role_name}}</p>
          <p>
            <el-select v-model="currentRolesId" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="assigningRolseVisible = false">取 消</el-button>
          <el-button type="primary" @click="setAssigningRolse">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    // 自动校验邮箱规则
    var checkEmail = (rule, vaule, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(vaule)) {
        // 合法邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 自动校验手机规则
    var checkMobile = (rule, vaule, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(vaule)) {
        return cb()
      }
      cb(new Error('请输入正确的手机号'))
    }
    return {
      // 获取用户列表的参数对象
      // query:查询参数
      // pagenum:当前的页数
      // pagesize:当前每页显示多少条数据
      queryInfo: { query: '', pagenum: 1, pagesize: 2 },
      // 用户列表数据
      UsersList: [],
      // 总页数
      total: 0,
      // 添加用户的显示隐藏对话框
      dialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 表单规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名的长度在3~10个字符之间',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 16,
            message: '用户名的长度在6~16个字符之间',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 修改用户弹窗显示隐藏
      editDialogVisible: false,
      // 存储用户数据
      editUsers: {},
      // 修改用户表单规则
      editUserRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 修改分配角色弹窗显示隐藏
      assigningRolseVisible: false,
      // 需要被分配的角色信息
      userInfo: {},
      // 存储从数据库获取的角色列表
      rolesList: [],
      // 选择器绑定属性
      currentRolesId: ''
    }
  },

  created () {
    // 获取用户列表的参数
    this.getUsersList()
  },
  methods: {
    // 获取用户列表的参数
    async getUsersList () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.UsersList = res.data.users
      this.total = res.data.total
      console.log(res)
    },
    // 监听每页显示多少条数据改变的事件
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUsersList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUsersList()
    },
    // 修改用户状态
    async modifyUserStatus (userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        res.mg_state = !res.mg_state
        return this.$message.error('更新用户失败')
      }
      this.$message.success('更新成功')
    },
    // 表单关闭重置表单
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户
    addUser () {
      this.$refs.addFormRef.validate(async val => {
        // 校验失败之后不在往下运行
        if (!val) return
        const { data: res } = await this.$http.post('users', this.addForm)
        console.log(res)
        // 可以发起添加用户的网络请求
        if (res.meta.status !== 201) {
          return this.$message.error('用户添加失败')
        }
        this.$message.success('用户添加成功')
        // 添加成功后隐藏添加用户的对话框
        this.dialogVisible = false
        // 重新获取用户列表
        this.getUsersList()
      })
    },
    // 获取用户
    async acquireUsers (id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editUsers = res.data
      this.editDialogVisible = true
    },
    // 重置修改表单
    editDialogClosed () {
      this.$refs.editUserRef.resetFields()
    },
    // 修改用户
    editUser () {
      this.$refs.editUserRef.validate(async val => {
        if (!val) return
        const { data: res } = await this.$http.put(
          'users/' + this.editUsers.id,
          {
            email: this.editUsers.email,
            mobile: this.editUsers.mobile
          }
        )
        // console.log(res)
        if (res.meta.status !== 200) {
          return this.$message.error('修改失败')
        }
        this.$message.success('更新成功')
        this.editDialogVisible = false
        this.getUsersList()
      })
    },
    // 删除用户
    async rmUserId (id) {
      const confirm = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      if (confirm !== 'confirm') {
        return this.$message.info('取消删除成功！')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getUsersList()
    },
    // 获得分配角色
    async getAssigningRolse (userInfo) {
      this.userInfo = userInfo
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.rolesList = res.data
      console.log(this.rolesList)

      this.assigningRolseVisible = true
    },
    // 提交分配角色
    async setAssigningRolse () {
      if (!this.currentRolesId) {
        return this.$message.error('请选择要分配的角色')
      }
      console.log(this.userInfo.id)

      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`,
        { rid: this.currentRolesId })
      console.log(res)

      if (res.meta.status !== 200) {
        return this.$message.error('分配角色失败')
      }
      this.$message.success('分配角色成功')
      this.getUsersList()
      this.assigningRolseVisible = false
    },
    // 重置分配角色弹框
    setRolesClose () {
      this.currentRolesId = ''
      this.userInfo = {}
    }
  }
}
</script>

<style lang="less" scoped>
</style>
